package com.booksystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.common.RestResult;
import com.booksystem.dto.CreatePaymentDTO;
import com.booksystem.dto.HandleCallbackDTO;
import com.booksystem.dto.QueryPaymentStatusDTO;
import com.booksystem.entity.OrderDO;
import com.booksystem.entity.PaymentDO;
import com.booksystem.entity.UserDO;
import com.booksystem.exception.BusinessException;
import com.booksystem.mapper.OrderMapper;
import com.booksystem.mapper.PaymentMapper;
import com.booksystem.mapper.UserMapper;
import com.booksystem.service.PaymentService;
import com.booksystem.utils.ResultCodeConstant;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   支付管理服务实现类
 * </p>
 * @author 段伟豪
 */
@Slf4j
@Service
@Transactional
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public RestResult<?> createPaymentOrder(CreatePaymentDTO createPaymentDTO) {
        // 校验用户是否存在
        UserDO userDO = userMapper.selectById(createPaymentDTO.getUserId());
        if (userDO == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, null);
        }

        // 校验订单是否存在且属于该用户
        QueryWrapper<OrderDO> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_id", createPaymentDTO.getOrderId())
                .eq("user_id", createPaymentDTO.getUserId());
        OrderDO orderDO = orderMapper.selectOne(orderQueryWrapper);
        if (orderDO == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "订单信息错误", null);
        }

        // 判断订单状态是否为待付款
        if (orderDO.getOrderStatus() != 1) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "订单状态不正确", null);
        }

        // 生成支付流水号并保存支付记录
        PaymentDO paymentDO = new PaymentDO();
        paymentDO.setUserId(createPaymentDTO.getUserId());
        paymentDO.setOrderId(createPaymentDTO.getOrderId());
        paymentDO.setTradeNo(UUID.randomUUID().toString().replaceAll("-", ""));
        paymentDO.setTransactionId("");
        paymentDO.setAmount(createPaymentDTO.getAmount());
        paymentDO.setPaymentMethod(createPaymentDTO.getPaymentMethod());
        paymentDO.setStatus(0); // 待支付
        paymentDO.setCreateBy("系统");
        paymentDO.setUpdateBy("系统");

        boolean insertSuccess = paymentMapper.insert(paymentDO) > 0;
        if (!insertSuccess) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "创建支付订单失败");
        }

        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, paymentDO);
    }

    @Override
    public RestResult<?> handlePaymentCallback(HandleCallbackDTO handleCallbackDTO) {
        // 根据商户订单号查找对应的支付记录
        QueryWrapper<PaymentDO> paymentQueryWrapper = new QueryWrapper<>();
        paymentQueryWrapper.eq("trade_no", handleCallbackDTO.getTradeNo());
        PaymentDO paymentDO = paymentMapper.selectOne(paymentQueryWrapper);
        if (paymentDO == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "支付记录不存在", null);
        }

        // 验证支付金额与原订单金额是否一致
        if (handleCallbackDTO.getAmount().compareTo(paymentDO.getAmount()) != 0) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "支付金额不符", null);
        }

        // 更新支付记录的状态及交易编号
        paymentDO.setTransactionId(handleCallbackDTO.getTransactionId());
        paymentDO.setStatus(handleCallbackDTO.getStatus());
        paymentDO.setUpdateBy("系统");
        boolean updateSuccess = paymentMapper.updateById(paymentDO) > 0;
        if (!updateSuccess) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "更新支付记录失败");
        }

        // 同步更新订单状态为已付款
        OrderDO orderDO = orderMapper.selectById(paymentDO.getOrderId());
        if (orderDO != null && orderDO.getOrderStatus() == 1) { // 只有当订单处于待付款状态时才更新
            orderDO.setOrderStatus(2); // 已付款
            orderDO.setUpdateBy("系统");
            boolean orderUpdateSuccess = orderMapper.updateById(orderDO) > 0;
            if (!orderUpdateSuccess) {
                throw new BusinessException(ResultCodeConstant.CODE_000001, "更新订单状态失败");
            }
        }

        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, paymentDO);
    }

    @Override
    public RestResult<?> queryPaymentStatus(QueryPaymentStatusDTO queryPaymentStatusDTO) {
        // 通过商户订单号获取支付记录
        QueryWrapper<PaymentDO> paymentQueryWrapper = new QueryWrapper<>();
        paymentQueryWrapper.eq("trade_no", queryPaymentStatusDTO.getTradeNo());
        PaymentDO paymentDO = paymentMapper.selectOne(paymentQueryWrapper);
        if (paymentDO == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "支付记录不存在", null);
        }

        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, paymentDO);
    }
}